﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using JDKill.Definitions;
using JDKill.Services;
using TDLib.UIs.Forms;
using TDLib.Utils;
using System.Diagnostics;
using System.Reflection;
using JDKill.Utils;
using JDKill.Definitions.Product;
using JDKill.Definitions.Address;
using JDKill.UIs.Common;
using JDKill.UIs.Login;
using JDKill.UIs.Query;
using System.Linq;

namespace JDKill.UIs
{
    public partial class FrmMain : FrmIconBase
    {
        private JDService _service = null;
        public bool _isMonitorRunning = false;
        private Thread _monitorThread = null;
        private long _outputRows = 0;
        private static ILog Logger = LoggerManager.GetLogger<FrmMain>();

        public FrmMain()
        {
            InitializeComponent();
            GlobalContext.MainForm = this;
            _service = GlobalContext.KillService;
            InitUI();
            InitSkin();
            Logger.Info("主窗体已初始化！");
            var dic = GlobalContext.KillService.QueryMiaoShaGroup();
            foreach (var item in dic)
	        {
                ProductCategory.AllCategory.Add(new ProductCategory(item.Key, item.Value,true));
	        } 
        }

        private void InitUI()
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            // 初始化版本号
            string version = Assembly.GetEntryAssembly().GetName().Version.ToString(3);
            this.Text += " v" + version;
            // 初始化窗体尺寸
            this.Width = 1245;
            this.Height = 764;
            // 初始化托盘双击事件
            this.notifyIcon1.MouseDoubleClick +=(o,args)=>
                {
                    if (args.Button == System.Windows.Forms.MouseButtons.Left)
                    {
                        this.notifyIcon1.Visible = false;
                        this.Show();
                        this.WindowState = FormWindowState.Normal;
                    }
                };
            Dictionary<string,PanelBase> queryControls = new Dictionary<string,PanelBase>();
            queryControls.Add("购物车", new PanelQueryCart());
            foreach (var item in queryControls)
	        {
                this.tabControl1.TabPages.Add(item.Key);
                item.Value.Dock = DockStyle.Fill;
                this.tabControl1.TabPages[this.tabControl1.TabPages.Count - 1].Controls.Add(item.Value);
	        }
        }

        private void InitSkin()
        {
            string resFileName = "OSX (Panther).vssf";
            string skinFile = ResUtil.GetResAsTempFile(resFileName, resFileName, true);
            this.visualStyler1.LoadVisualStyle(skinFile);
        }

        private void toolStripButtonQuery_Click(object sender, EventArgs e)
        {
            // 获取查询参数
            List<ProductCategory> categoryList = this.panelQueryProduct1.GetQueryCategoryList();
            if (categoryList.Count == 0)
            {
                MsgBox.Warning("请选择筛选种类！");
                return;
            }
            string locationId = this.panelQueryProduct1.GetLocationId();
            if (locationId == null)
            {
                MsgBox.Warning("请选择配置至！");
                return;
            }
            string locationName = this.panelQueryProduct1.GetLocationName();
            // 设置控件状态
            this.toolStripButtonQuery.Enabled = false;
            this.toolStripButtonMonitor.Enabled = false;

            DoOutput("正在查询...");
            this.panelQueryProduct1.ClearProductList();
            RunTaskThread(() => DoQuery(categoryList, locationId, locationName));
        }

        private void toolStripButtonMonitor_Click(object sender, EventArgs e)
        {
            if (!GlobalContext.IsLogined())
                return;

            if (this.toolStripButtonMonitor.Tag == null)
            {
                // 获取抢购列表
                List<ProductDetail> neededProductList = this.panelProductKillSetting1.GetProductListInNeed();
                if (neededProductList.Count < 1)
                {
                    MsgBox.Warning("请先添加需要抢购的商品！");
                    return;
                }
                // 获取收货地址
                AddressDetail address = this.panelProductKillSetting1.GetAddress();
                if (address == null)
                {
                    MsgBox.Warning("请先选择收货地址！");
                    return;
                }
                // 获取下单条件
                MakeOrderCondition condition = this.panelProductKillSetting1.GetMakeOrderCondition();
                double certainPrice = this.panelProductKillSetting1.GetCertainPrice();
                if (condition == MakeOrderCondition.WhenAvailableAndLessEqualCertainPrice)
                {
                    if (certainPrice == -1)
                    {
                        MsgBox.Warning("请输入有效的下单价格！");
                        return;
                    }
                }
                _monitorThread = new Thread(() => DoMonitor(neededProductList, address,condition,certainPrice));
                _monitorThread.IsBackground = true;
                _monitorThread.Start();
                this.toolStripButtonMonitor.Text = "停止抢购";
                this.toolStripButtonMonitor.Tag = "";
            }
            else
            {
                DoOutput("正在停止抢购...");
                this.toolStripButtonMonitor.Enabled = false;
                this.toolStripButtonMonitor.Text = "停止中";
                _isMonitorRunning = false;
            }
        }

        private void toolStripButtonLoginOrLogout_Click(object sender, EventArgs e)
        {
            var frm = new FrmLogin();
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    var userInfo = _service.QueryUserInfoDetail();
                    if (userInfo == null)
                    {
                        throw new Exception("未登陆");
                    }
                    DoOutput("登陆成功：" + userInfo.LoginName);
                    this.toolStripStatusLabel1.Text = "用户：" + userInfo.LoginName;
                    this.toolStripStatusLabel1.Tag = userInfo;
                    GlobalContext.SetLoginState(true);
                    string cookie = _service.GetCookie();
                    ConfigStorage.SaveUser(userInfo.Id, cookie);
                    Console.WriteLine(cookie);
                }
                catch (Exception ex)
                {
                    DoOutput("登录失败," + ex.Message);
                    this.toolStripStatusLabel1.Text = "用户";
                    this.toolStripStatusLabel1.Tag = null;
                    GlobalContext.SetLoginState(false);
                }
            }
        }

        public void DoOutput(string str)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(() => DoOutput(str)));
                return;
            }
            _outputRows++;
            if (_outputRows > 300)
            {
                this.textBoxOutput.Clear();
                _outputRows = 0;
            }
            this.textBoxOutput.Text = DateTime.Now.ToString() + " " + str + "\r\n" + this.textBoxOutput.Text;
        }

        private void DoQuery(List<ProductCategory> categoryList, string locationId, string locationName)
        {
            // 保存配置
            ConfigStorage.SaveLocationId(locationId);
            ConfigStorage.SaveLocationName(locationName);

            // 查询接口数据
            var productDic = new Dictionary<ProductCategory, List<ProductDetail>>();
            foreach (var category in categoryList)
            {
                try
                {
                    DoOutput("查询种类：" + category.Name);
                    List<ProductDetail> list = null;
                    if (category.IsKill)
                    {
                        list = GlobalContext.KillService.QueryMiaoShaoProductsByGroup(category.Id, locationId);
                        // 按照打折率，从低到高进行排列
                        list = list.OrderBy(p => p.KillPrice / p.Price).ToList();
                    }
                    else
                    {
                        list = _service.QueryProductDetailList(category, locationId);
                    }
                    productDic.Add(category, list);
                }
                catch (Exception ex)
                {
                    DoOutput("查询接口失败，" + ex.Message);
                }
            }
            RunTaskInvoke(() => {
                // 渲染数据
                this.panelQueryProduct1.RenderProductList(productDic);
                DoOutput("共查询到：" + this.panelQueryProduct1.GetProductRowCount() + "个！");
                this.toolStripButtonMonitor.Enabled = true;
                this.toolStripButtonQuery.Enabled = true;
            });
        }

        private void DoMonitor(List<ProductDetail> neededProductList, AddressDetail address,
            MakeOrderCondition condition, double certainPrice)
        {
            DoOutput("开始抢购...");
            foreach (var item in neededProductList)
	        {
                Logger.Info(string.Format("开始抢购\r\n商品id:{0}\r\n商品名称:{1}", item.Id, item.Name));
	        }
            
            _isMonitorRunning = true;
            this.toolStripButtonQuery.Enabled = false;
            this.toolStripButtonLoginOrLogout.Enabled = false;
            bool isQueryPrice = false;
            while (true)
            {
                foreach (var product in neededProductList)
                {
                    try
                    {
                        if (condition == MakeOrderCondition.WhenAvailableAndLessEqualCertainPrice)
                        {
                            isQueryPrice = true;
                        }
                        else if (condition == MakeOrderCondition.WhenAvailable)
                        {
                            isQueryPrice = false;
                        }
                        else
                        {
                            throw new Exception("未定义类型" + condition);
                        }
                        var curProduct = _service.QueryProductDetail(product.Id, address.GetLocationId(), isQueryPrice);
                        // 判断商品是否可购
                        if (curProduct.IsBuyAvailable())
                        {
                            if (condition == MakeOrderCondition.WhenAvailableAndLessEqualCertainPrice)
                            {
                                // 判断商品价格是否小于等于指定价格
                                if (curProduct.Price > certainPrice)
                                {
                                    DoOutput(string.Format("{0}，有货但不满足指定价格(当前价格:{1})", curProduct.Name, curProduct.Price));
                                    continue;
                                }
                            }
                            DoOutput("检测到商品可购：" + curProduct.Name);

                            string msg = "亲," + curProduct.Name + ",";
                            bool isAutoCreateOrder = this.panelProductKillSetting1.IsAutoCreateOrder;
                            if (isAutoCreateOrder)
                            {
                                DoOutput("开始自动下单...");
                                _service.CreateOrder(curProduct, 1, address);
                                DoOutput("下单成功，请在手机上及时支付！");
                                msg += "抢到了!"; ;
                            }
                            else
                            {
                                msg += "有货了!"; ;
                            }

                            try
                            {
                                DoTip(msg);
                            }
                            catch
                            {
                            }
                            _isMonitorRunning = false;
                            break;
                        }
                        else
                        {
                            DoOutput(product.Name + "，无货");
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Error(string.Format("监控商品异常\r\n商品id:{0}\r\n商品名称:{1}",product.Id,product.Name), ex);
                        if (ex.Message.Contains("创建订单失败"))
                        {
                            DoOutput(ex.Message);

                            _isMonitorRunning = false;
                            break;
                        }
                        DoOutput("监控商品：" + product.Name + "异常，" + ex.Message);
                    }
                }

                if (!_isMonitorRunning)
                    break;

                bool customQueryInterval = this.panelProductKillSetting1.IsCustomQueryInterval;
                int minInterval = this.panelProductKillSetting1.GetCustomMinQueryInterval();
                int maxInterval = this.panelProductKillSetting1.GetCustomMaxQueryInterval();
                if (!customQueryInterval)
                {
                    minInterval = 800;
                    maxInterval = 1300;
                }
                int interval = new Random((int)DateTime.Now.Ticks).Next(minInterval, maxInterval);
                Thread.Sleep(interval);
            }

            _isMonitorRunning = false;
            this.toolStripButtonQuery.Enabled = true;
            this.toolStripButtonMonitor.Enabled = true;
            this.toolStripButtonLoginOrLogout.Enabled = true;
            this.toolStripButtonMonitor.Text = "开始抢购";
            this.toolStripButtonMonitor.Tag = null;
            DoOutput("已停止抢购！");
        }

        /// <summary>
        /// 抢购提示
        /// </summary>
        /// <param name="msg"></param>
        private void DoTip(string msg)
        {
            //气泡提醒
            ShowBalloonTip(msg);

            //声音提醒
            this.panelAudioNotifierSetting1.Play();

            //QQ提醒
            this.panelQQNotifierSetting1.SendQQMessage(msg);
        }

        /// <summary>
        /// 在系统托盘显示气泡信息
        /// </summary>
        /// <param name="tipText">提示信息</param>
        private void ShowBalloonTip(string tipText)
        {
            this.notifyIcon1.ShowBalloonTip(3000, "提示", tipText, ToolTipIcon.Info);
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            this.panelAudioNotifierSetting1.Init(this.Handle);
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            string appName = this.Text;
            if (MessageBox.Show("确定要退出" + appName + "？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) !=
                DialogResult.OK)
            {
                e.Cancel = true;
            }
        }

        private void FrmMain_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                this.notifyIcon1.Icon = this.Icon;
                this.notifyIcon1.Text = this.Text;
                this.notifyIcon1.Visible = true;
                ShowBalloonTip("我在这里！");
            }
        }

        private void panelQueryProduct1_AddToProductKillList(object sender, AddToProductKillListEventArgs e)
        {
            if (!this.panelProductKillSetting1.GetProductListInNeed().Exists(m => m.Equals(e.Product)))
            {
                this.panelProductKillSetting1.AddToProductListInNeed(e.Product);
            }
        }

        /// <summary>
        /// “常用地址”按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButtonCommonUrl_ButtonClick(object sender, EventArgs e)
        {
            for (int i = this.toolStripButtonCommonUrl.DropDownItems.Count - 2; i >= 0; i--)
            {
                this.toolStripButtonCommonUrl.DropDownItems.RemoveAt(i);
            }
            // 初始化常用链接
            var commonUrl = ConfigStorage.ReadAllCommonUrl();
            foreach (var pair in commonUrl)
            {
                string name = pair.Key;
                string url = pair.Value;
                ToolStripItem item = new ToolStripButton(name, null, (o, args) =>
                {
                    ToolStripItem tsi = o as ToolStripItem;
                    string u = tsi.Tag.ToString();
                    try
                    {
                        Process.Start(u);
                    }
                    catch (Exception ex)
                    {

                    }
                });
                item.Tag = url;
                this.toolStripButtonCommonUrl.DropDownItems.Insert(0, item);
            }
            this.toolStripButtonCommonUrl.ShowDropDown();
        }

        private void 添加常用地址ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var frm = new FrmAddCommonUrl();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                string name = frm.UrlName;
                string url = frm.UrlValue;
                ConfigStorage.SaveCommonUrl(name,url);
            }
        }

        /// <summary>
        /// 启用定时抢购
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void panelUniversalSetting1_OnTimerKillEnabled(object sender, EventArgs e)
        {
            if (!GlobalContext.IsLogined())
            {
                this.panelUniversalSetting1.DoDisableTimerKill();
                return;
            }
            if (this._isMonitorRunning)
            {
                MsgBox.Warning("请先停止抢购！");
                this.panelUniversalSetting1.DoDisableTimerKill();
                return;
            }
            // 获取抢购列表
            List<ProductDetail> neededProductList = this.panelProductKillSetting1.GetProductListInNeed();
            if (neededProductList.Count < 1)
            {
                MsgBox.Warning("请先添加需要抢购的商品！");
                this.panelUniversalSetting1.DoDisableTimerKill();
                return;
            }
            // 获取收货地址
            AddressDetail address = this.panelProductKillSetting1.GetAddress();
            if (address == null)
            {
                MsgBox.Warning("请先选择收货地址！");
                this.panelUniversalSetting1.DoDisableTimerKill();
                return;
            }
            // 获取下单条件
            MakeOrderCondition condition = this.panelProductKillSetting1.GetMakeOrderCondition();
            double certainPrice = this.panelProductKillSetting1.GetCertainPrice();
            if (condition == MakeOrderCondition.WhenAvailableAndLessEqualCertainPrice)
            {
                if (certainPrice == -1)
                {
                    MsgBox.Warning("请输入有效的下单价格！");
                    this.panelUniversalSetting1.DoDisableTimerKill();
                    return;
                }
            }
            if (this.panelUniversalSetting1.KillTimer <= DateTime.Now)
            {
                MsgBox.Warning("定时抢购时间必须比当前时间大！");
                this.panelUniversalSetting1.DoDisableTimerKill();
                return;
            }
            DoOutput("已启动定时抢购！");
            this.toolStripButtonMonitor.Enabled = false;
            this.panelUniversalSetting1.StartChecker();
        }

        /// <summary>
        /// 禁用定时抢购
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void panelUniversalSetting1_OnTimerKillDisabled(object sender, EventArgs e)
        {
            this.panelUniversalSetting1.StopChecker();
        }

        /// <summary>
        /// 定时器触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void panelUniversalSetting1_OnTimerKillTrigger(object sender, EventArgs e)
        {
            this.toolStripButtonMonitor.Enabled = true;
            toolStripButtonMonitor_Click(null, null);
        }
    }
}
